import React, {useEffect, useState} from 'react';
import {
  ActivityIndicator,
  Dimensions,
  FlatList,
  Image,
  Text,
  View,
} from 'react-native';
import {useCardListProvider} from '../../../hooks/useCardListProvider';
import {primaryColor, primaryColor2} from '../../../theme/default';
import {CardWithAddress} from '../../../db/models/cardModel';
import {CardItem} from './CardItem';
import {AddCardButton} from './AddCardButton';
import {useNavigation} from '@react-navigation/native';
import {RootStackParamList} from '../../Nav/routes';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {UpNetworkLogo} from '../UpNetworkLogo';
import SimpleModal from '../Common/SimpleModal';
import {IdentityModel} from '../../../db/models/identityModel';
import {useAuthProvider} from '../../../hooks/useAuthProvider';
import LoadingModal from '../Common/LoadingModal';
import {useTranslation} from 'react-i18next';

const {width} = Dimensions.get('window');

export function CardList() {
  const {loading, cards, unbinding, unbind, getCards} = useCardListProvider();

  const [currentItem, setCurrentItem] = useState<CardWithAddress>();
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const {logout} = useAuthProvider();

  const {t} = useTranslation();

  useEffect(() => {
    console.log('unbinding', unbinding);
  }, [unbinding]);

  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList>>();

  const renderCardItem = ({item}: {item: CardWithAddress}) => (
    <CardItem
      card={item}
      onPress={e => {
        if (unbinding) {
          return;
        }
        setCurrentItem(item);
        setIsModalVisible(true);
      }}
    />
  );

  return (
    <>
      {loading ? (
        <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
          <ActivityIndicator size="small" color={primaryColor} />
        </View>
      ) : (
        <>
          {cards.length == 0 ? (
            <View
              style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
              <View
                style={{
                  position: 'absolute',
                  justifyContent: 'center',
                  alignItems: 'center',
                  top: 48,
                }}>
                <UpNetworkLogo color={primaryColor}></UpNetworkLogo>
              </View>
              <View style={{marginBottom: 48}}>
                <Image
                  style={{width: 160, height: 160}}
                  source={require('../../../assets/images/card.png')}></Image>
              </View>
              <View
                style={{
                  width: width - 32,
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginBottom: 12,
                }}>
                <Text
                  style={{
                    color: primaryColor2,
                    fontSize: 15,
                    fontWeight: '600',
                  }}>
                  {t('noCardHint')}
                </Text>
              </View>
              <AddCardButton
                type="init"
                width={width - 32}
                onPress={() => {
                  navigation.navigate('AddCard');
                }}></AddCardButton>
              <View
                style={{
                  width: width - 32,
                  marginTop: 32,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Text style={{color: primaryColor2}}>{t('cardDesc')}</Text>
              </View>
            </View>
          ) : (
            <View style={{flex: 1, alignItems: 'center'}}>
              <FlatList
                showsVerticalScrollIndicator={false}
                style={{width: width - 24, marginTop: 12}}
                data={cards}
                renderItem={renderCardItem}
                keyExtractor={item => item.solanaAddress}
              />
              <View
                style={{
                  height: 140,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <AddCardButton
                  type="common"
                  width={'90%'}
                  onPress={() => {
                    navigation.navigate('AddCard');
                  }}></AddCardButton>
              </View>
              <SimpleModal
                visible={isModalVisible}
                title={t('unbindCard')}
                content={t('unbindCardHint')}
                onCancel={() => {
                  setIsModalVisible(false);
                }}
                onConfirm={() => {
                  setIsModalVisible(false);
                  setTimeout(() => {
                    currentItem &&
                      unbind(currentItem!.userName)
                        .then(async () => {
                          //if the card wallet is seleted one, logout
                          const identityModel = new IdentityModel();
                          const identity = await identityModel.getSelected();
                          if (identity == null) {
                            logout();
                          } else {
                            getCards();
                          }
                        })
                        .catch(error => {
                          //toast try again
                          console.log(error);
                        });
                  }, 1000);
                }}></SimpleModal>
              <LoadingModal visible={unbinding}></LoadingModal>
            </View>
          )}
        </>
      )}
    </>
  );
}
